package servlets;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmput391.src.queries.DBConnector;
import cmput391.src.queries.SecurityQueries;
import cmput391.src.queries.UserManagementQueries;

/**
 * Servlet implementation class JsonDoctorList
 */
@WebServlet("/JsonDoctorList")
public class JsonDoctorList extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JsonDoctorList() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DBConnector dbConnect = new DBConnector();
		SecurityQueries security = null;
		
		String term = request.getParameter("term").toLowerCase();
		
		try {
			security = new SecurityQueries(dbConnect.getConnection());
			UserManagementQueries umq = new UserManagementQueries(dbConnect.getConnection(), security);
			ArrayList<String> allDoctors = new ArrayList<String>();
			allDoctors.addAll(umq.getAllOfClass("d"));
			String jsonDoctors = "[";
			int i=1;
			for (String doctor : allDoctors) {
				String lowerCaseDoctor = doctor.toLowerCase();
				if (lowerCaseDoctor.contains(term)) {
					if (i > 1)
						jsonDoctors +=", ";					
					jsonDoctors += "\""+doctor+"\"";

					i++;
				}
			}
					
			jsonDoctors += "]";
			System.out.println(jsonDoctors);
			response.setContentType("application/json");
			// Get the printwriter object from response to write the required json object to the output stream      
			PrintWriter out = response.getWriter();
			// Assuming your json object is **jsonObject**, perform the following, it will return your json object  
			out.print(jsonDoctors);
			out.flush();
		}
		catch (Exception e) {
			response.sendError(500);
			request.getRequestDispatcher("report.jsp").forward(request, response);				
		    e.printStackTrace();
		}
	}

}
